//首页
import React, { useEffect, useState } from 'react';
import { Image, Text, View } from '@tarojs/components';
import './index.less';
import TitleBar from 'src/components/titleBar';
import Taro, { useDidShow } from '@tarojs/taro';

import BottomContainer from '@/src/components/bottomContainer';
import { getListFun } from '@/src/common/method/activityFun';
import { activityList } from '@/src/common/util/contant';
import CommonBlank from '@/src/components/pageBlank';
import LoadingSpinner from '@/src/components/loadingSpinner';
import InlinePanel from '@/src/components/inlinePanel';
import CitySelector from '@/src/components/citySelector';
import ActicityItem from '@/src/components/acticityItem';
import { observer } from 'mobx-react-lite';
import store from '@/src/store';
import { getConversionFun } from '@/src/common/method/commonFun';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';
import { ensureLocationAuth } from '@/src/utils/locationAuth';
//活动列表
const Home = () => {
  const [current, setCurrent] = useState<any>(0); //选中的是活动还是城市
  const [select, setSelect] = useState(null);
  const [selectActivityName, setSelectActivityName] = useState<any>('全部活动');

  const [sortOrder, setSortOrder] = useState('DESC'); //排序方式desc降序，asc升序
  const [dataList, setDataList] = useState([]);
  const [loadingText, setLoadingText] = useState<any>('加载中...');
  // 省份的code
  const [provinceCode, setProvinceCode] = useState<string>('');
  const [selectName, setSelectName] = useState<any>('北京'); //选择的市name
  //城市编码
  const [cityCode, setCityCode] = useState<any>('110000');
  const isIos: any = store.commonStore.isIos;
  useDidShow(() => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });
  //获取活动列表
  const getList = (selectName: any) => {
    getListFun({
      regionName: selectName,
      sortOrder: sortOrder,
      activityStatus: select,
    }).then((res: any) => {
      setLoadingText('');
      if (select === null) {
        setDataList(res.list);
      } else {
        let result: any = res.list.filter(
          (item: any) => item.activityStatus === select
        );
        setDataList(result);
      }
    });
  };

  // 获取定位权限
  const getLocationFun = async () => {
    // 先确保授权（若被拒会弹自定义弹窗，引导去设置）
    const ok = await ensureLocationAuth();
    if (!ok) {
      // 未授权：保留默认位置，直接按默认拉数据
      console.warn('定位未授权');
      getList(selectName);

      return;
    }
    // 已授权 → 真正取定位
    try {
      const loc: any = await Taro.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        highAccuracyExpireTime: 3000,
      });
      const location = `${loc.latitude},${loc.longitude}`;
      try {
        const res: any = await getConversionFun(location);
        setCityCode(res.city.areaCode);
        setProvinceCode(res.province.areaCode);
        store.commonStore.setCity(res.city.areaName);
        store.commonStore.setCityCode(res.city.areaCode);
        store.commonStore.setProvinceCode(res.province.areaCode);
        store.commonStore.setProvince(res.province.areaName);
        console.log(res, '返回授权的地址');
        // 获取商店列表（用真实城市名）
        getList(res.city.areaName);
      } catch (err: any) {
        console.log(err, 'err');
      }
    } catch {
      // 获取定位异常：回退默认
      console.warn('获取定位失败，使用默认位置');
      getList(selectName);
    }
  };
  useEffect(() => {
    getLocationFun();
  }, [sortOrder]);
  //展示全部活动弹窗
  const showAllModal = (val: any) => {
    if (current === val) {
      setCurrent('');
    } else {
      setCurrent(val);
    }
  };

  //跳转详情
  const gotoDetail = (item: any) => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.navigateTo({
      url: `/subPagesActivity/detail/index?activityId=${encodeURIComponent(item.activityId)}&showBtn=true`,
    });
  };

  useEffect(() => {
    getList(selectName);
  }, [select]);
  //选择活动
  const handleSelectActivity = (item: any) => {
    console.log('val=====', item);
    setSelectActivityName(item.name);
    setSelect(item.id);
    setCurrent(0);
  };

  const content = () => {
    return (
      <View>
        {activityList.map((item: any, index: any) => {
          return (
            <View
              key={index}
              className="home-activity-header-modal-item"
              onClick={() => handleSelectActivity(item)}
            >
              <Text>{item.name}</Text>
              {item.id === select && (
                <Image
                  src={
                    'https://file.linkcook.cn/image/wineMiniProgram/activity/select.png'
                  }
                />
              )}
            </View>
          );
        })}
      </View>
    );
  };

  const handleSelect = (city: any) => {
    setSelectName(city.areaName);
    setCityCode(city.areaCode);
    setProvinceCode(city.provinceCode);
    setCurrent(0);
    getList(city.areaName);
  };
  return (
    <View
      className="home-activity-container"
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
    >
      <TitleBar showLeftBack={true} title="活动"></TitleBar>
      <View
        className="home-activity-header"
        style={{ top: store.commonStore.isIos ? '94px' : '90px' }}
      >
        <View
          className="home-activity-header-item"
          onClick={() => showAllModal('city')}
        >
          举办城市
          <Image
            src={'https://file.linkcook.cn/image/wineMiniProgram/wiki/down.png'}
          />
        </View>
        <View
          className="home-activity-header-item"
          onClick={() => showAllModal('status')}
        >
          {selectActivityName}
          <Image
            src={'https://file.linkcook.cn/image/wineMiniProgram/wiki/down.png'}
          />
        </View>
        <View
          className="home-activity-header-item"
          onClick={() => setSortOrder(sortOrder === 'DESC' ? 'ASC' : 'DESC')}
        >
          举办时间
          <View className={`home-activity-arrow ${sortOrder}`}>
            <View className="home-activity-up"></View>
            <View className="home-activity-down"></View>
          </View>
        </View>
      </View>
      {/* 活动弹框内容 */}
      {current === 'status' && (
        <View className="home-activity-header-modal">
          <InlinePanel
            visible={current === 'status'}
            mask={true}
            activity={true}
            onClose={() => {
              setCurrent(0);
            }}
            content={content()}
          ></InlinePanel>
        </View>
      )}
      {/*举办城市弹框内容*/}
      {current === 'city' && (
        <View className="modal-city-container">
          <InlinePanel
            visible={current === 'city'}
            mask={true}
            activity={true}
            onClose={() => {
              setCurrent(0);
            }}
            content={
              <CitySelector
                onClose={() => setCurrent(0)}
                initialProvinceCode={provinceCode}
                initialCityCode={cityCode}
                onSelect={(val: any) => {
                  handleSelect(val);
                }}
              ></CitySelector>
            }
          ></InlinePanel>
        </View>
      )}
      {/* 空页面 */}
      {dataList && dataList.length === 0 && (
        <CommonBlank
          blank={
            'https://file.linkcook.cn/image/wineMiniProgram/exception/empty_activity.png'
          }
          visible={true}
          desc="抱歉，暂无活动"
        />
      )}
      {/* 活动列表内容 */}
      {dataList && dataList.length > 0 && (
        <ActicityItem
          list={true}
          dataList={dataList}
          mine={true}
          goDetail={gotoDetail}
        />
      )}
      <LoadingSpinner text={loadingText} />
      <BottomContainer />
    </View>
  );
};

export default observer(Home);
